﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace winSpriteCreator
{
  public partial class Form1 : Form
  {
    private Bitmap _bmp;
    public ucSquare CurrentSquare { get; set; }
    public Form1()
    {
      InitializeComponent();


    }

    private void SavePictureFile()
    {

      Bitmap pic = new Bitmap((int)(nudColumns.Value*nudWidth.Value), (int)(nudRows.Value*nudHeight.Value));
      Graphics g = Graphics.FromImage(pic);

      int squareWidth = (int) nudWidth.Value;
      int squareHeight = (int)nudHeight.Value;
      
      for (int y = 0; y < nudRows.Value; y++)
      {

        int mapHeight = y*squareHeight;


        for (int x = 0; x < nudColumns.Value; x++)
        {
          int mapWidth = x*squareWidth;

          ucSquare sq = FindSquare(x, y);
          if( sq != null && sq.CurrentImage != null)
          {


            int x2 = (x*squareWidth) + (squareWidth/2 - sq.CurrentImage.Size.Width/2);
            int y2 = (y * squareHeight) + (squareHeight / 2 - sq.CurrentImage.Size.Height / 2);
            g.DrawImage(sq.CurrentImage,x2, y2);
          }
        }
      }

      saveFileDialog1.ShowDialog(this);
      pic.Save(saveFileDialog1.FileName);
    }

    private void button1_Click(object sender, EventArgs e)
    {
      AddUserControls(Convert.ToInt32(nudColumns.Value),
                        Convert.ToInt32(nudRows.Value),
                        Convert.ToInt32(nudWidth.Value),
                        Convert.ToInt32(nudHeight.Value));
      /*
      Bitmap bmp = CreateBitMap();
      AddLinesToBitmap(ref bmp);
      pbResult.Image = bmp;
      _bmp = bmp;
       * */
      
    }

    private Bitmap CreateBitMap()
    {
      Bitmap bmp = new Bitmap((int)(nudColumns.Value*nudWidth.Value) + (int)((nudColumns.Value-1)), (int)(nudRows.Value*nudHeight.Value)+(int)(nudRows.Value-1), PixelFormat.Format32bppArgb);
     
      return bmp;
    }

    private void AddLinesToBitmap(ref Bitmap bmp)
    {
      Graphics g = Graphics.FromImage(bmp);
      g.FillRectangle(new SolidBrush(pbBackGround.BackColor), new Rectangle(0, 0, bmp.Size.Width, bmp.Size.Height));
      
      // Vertical Lines
      for(int index=1; index<nudColumns.Value; index++ )
      {
        g.DrawLines(new Pen(pbLines.BackColor), new Point[]
                                                      {
                                                        new Point((int)(index*(nudWidth.Value+1))+1,0),
                                                        new Point((int)(index*(nudWidth.Value+1))+1,bmp.Size.Height) 
                                                      } );
      }

      // Horzontal Lines
      for (int index = 1; index < nudColumns.Value; index++)
      {
        g.DrawLines(new Pen(pbLines.BackColor), new Point[]
                                                      {
                                                        new Point(0, (int)(index*(nudHeight.Value+1))+1),
                                                        new Point(bmp.Size.Width,(int)(index*(nudHeight.Value+1))+1) 
                                                      });
      }
    }

    private void AddRowOfSprites( ref Bitmap bmp, string[] sprites, int row)
    {
      Graphics g = Graphics.FromImage(bmp);

      int width = Convert.ToInt32(nudWidth.Value);
      int height = Convert.ToInt32(nudHeight.Value);
      int square = 0;

      foreach( string fileName in sprites )
      {
        Image tempBmp = Bitmap.FromFile(fileName);

        g.DrawImage(tempBmp, (float)(square * width) - (width / 2 + tempBmp.Size.Width / 2) + ( square+1), (float)((row+1) * height) - (height / 2 + tempBmp.Size.Height / 2) + row);

        square++;
      }

    }

    private void AddRowOfSprites2(ucSquare startingSquare, string[] sprites)
    {
      //Graphics g = Graphics.FromImage(bmp);

      //int width = Convert.ToInt32(nudWidth.Value);
      //int height = Convert.ToInt32(nudHeight.Value);
      //int squareIndex = panel1.Controls.IndexOf(startingSquare);
      int x = CurrentSquare.X;
      int y = CurrentSquare.Y;
      ucSquare tempSquare;
      bool hasPrompted = false;
      for(int index =0; index<sprites.Length; index++, x++)
      {
        if (x > (int)(nudColumns.Value))
        {
          x = 0;
          y++;
        }

        CurrentSquare = FindSquare(x, y);

        //ucSquare currentSquare = FindSquare(x, y);
        if (CurrentSquare == null)
          continue;

        Image img = Image.FromFile(sprites[index]);
        if(!hasPrompted && (img.Size.Height > (int)(nudHeight.Value) || img.Size.Width > (int)(nudWidth.Value)))
        {
          DialogResult dr = MessageBox.Show(
            "The image selected is larger than the current squares.\nWould you like to enlarge the squares? If not and AutoSize is checked, the application will scale the images selected",
            "WARNING: Images different sizes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);

          hasPrompted = true;

          if (dr == DialogResult.Cancel)
            return;

          if( dr == DialogResult.Yes)
          {
            nudWidth.Value = (img.Size.Width > (int)(nudWidth.Value) ? img.Size.Width : (int)(nudWidth.Value));
            nudHeight.Value = (img.Size.Height > (int)(nudHeight.Value) ? img.Size.Height : (int)(nudHeight.Value));

            AddUserControls((int)(nudColumns.Value),
                            (int)(nudRows.Value),
                            (int)nudWidth.Value,
                            (int)nudHeight.Value);
            //width = Convert.ToInt32(nudWidth.Value);
            //height = Convert.ToInt32(nudHeight.Value);
          
          }
        } else {}


        if (chkAutoSize.Checked)
        {

          
          Graphics g = Graphics.FromImage(img);
          Bitmap bmp = new Bitmap(img, (int)(nudWidth.Value), (int)(nudHeight.Value));
          CurrentSquare.CurrentImage = bmp;
        }
        else
        {
          CurrentSquare.CurrentImage = img;
        }
        //g.DrawImage(bmp);
        
      }


    }

    private ucSquare FindSquare(int x, int y)
    {
      foreach(Control ctrl in panel1.Controls)
      {
        ucSquare ct = ctrl as ucSquare;

        if( ct != null )
        {
          if (ct.X == x && ct.Y == y)
            return ct;
        }
      }

      return null;
    }
    private void pictureBox1_Click(object sender, EventArgs e)
    {
      colorDialog1.AllowFullOpen = true;
      colorDialog1.ShowDialog(this);
      pbBackGround.BackColor = colorDialog1.Color;
    }

    private void pbLines_Click(object sender, EventArgs e)
    {
      colorDialog1.AllowFullOpen = true;
      colorDialog1.ShowDialog(this);
      pbLines.BackColor = colorDialog1.Color;
    }

    private void button2_Click(object sender, EventArgs e)
    {
      SavePictureFile();
//      saveFileDialog1.ShowDialog(this);
//      _bmp.Save(saveFileDialog1.FileName);
    }

    private void button3_Click(object sender, EventArgs e)
    {
      if( this.CurrentSquare == null )
      {
        MessageBox.Show("You must select a starting square first");
        return;
      }

      int x = CurrentSquare.X;
      int y = CurrentSquare.Y;
      MessageBox.Show("Please select all files that will be inserted on a row.");

      OpenFileDialog openFile = new OpenFileDialog();
      openFile.Multiselect = true;
      openFile.ShowDialog(this);

      if (openFile.FileNames.Length > 0)
      {
        AddRowOfSprites2(CurrentSquare, openFile.FileNames);
      }
      //AddRowOfSprites(ref _bmp, openFile.FileNames, (int)numInsertRow.Value);

      //pbResult.Refresh();
    }

    public void AddUserControls(int columns, int rows, int width, int height)
    {
      int dy = -1;
      int dx = -1;
      if( CurrentSquare != null )
      {
        dx = CurrentSquare.X;
        dy = CurrentSquare.Y;
      }

      panel1.Controls.Clear();
      for( int y=0; y<rows; y++)
      {
        for(int x=0; x<columns; x++)
        {
          ucSquare sq = new ucSquare();
          sq.Size = new Size(width, height);
          sq.Location = new Point(x*width, y*height);
          panel1.Controls.Add(sq);
          sq.Clicked += new ClickedEventHandler(SquareClicked);
          sq.X = x;
          sq.Y = y;
        }
      }

      this.CurrentSquare = null;

      if (dx != -1 && dy != -1)
      {
        this.CurrentSquare = FindSquare(dx, dy);
        this.CurrentSquare.BorderStyle = BorderStyle.Fixed3D;
      }
    }

    private void button4_Click(object sender, EventArgs e)
    {
      panel1.Controls.Clear();
    }

    private void SquareClicked(object sender, EventArgs e)
    {
      if( CurrentSquare != null)
        this.CurrentSquare.BorderStyle = BorderStyle.FixedSingle;
      this.CurrentSquare = (ucSquare)sender;
      this.CurrentSquare.BorderStyle = BorderStyle.Fixed3D;
      this.lblXCoord.Text = CurrentSquare.X.ToString();
      this.lblYCoord.Text = CurrentSquare.Y.ToString();
      this.pictureBox1.Image = CurrentSquare.CurrentImage;

    }

    private void button5_Click(object sender, EventArgs e)
    {

    }
  }
}
